package com.cgb2110.serve.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cgb2110.serve.pojo.Employee;
import com.cgb2110.serve.pojo.MailConstants;
import com.cgb2110.serve.pojo.MailLog;
import com.cgb2110.serve.service.impl.EmployeeServiceImpl;
import com.cgb2110.serve.service.impl.MailLogServiceImpl;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;



import java.time.LocalDateTime;
import java.util.List;

@Component
public class MailTask {
    @Autowired
    private MailLogServiceImpl mailLogService;
    @Autowired
    private EmployeeServiceImpl employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 邮件发送定时任务
     * 10秒执行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
        List<MailLog> mailLogs = mailLogService.list(new QueryWrapper<MailLog>().
                eq("status", 0).
                lt("tryTime", LocalDateTime.now()));
        mailLogs.forEach(mailLog -> {
            if (3<=mailLog.getCount()){
                mailLogService.update(new UpdateWrapper<MailLog>().set("status", 2).eq("msgId", mailLog.getMsgId()));
                mailLogService.update(new UpdateWrapper<MailLog>().
                        set("count", mailLog.getCount()+1 ).
                        set("updateTime", LocalDateTime.now()).
                        set("tryTime", LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT)));

                Employee employee = employeeService.getEmployee(mailLog.getEid()).get(0);
                rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,
                        MailConstants.MAIL_ROUTING_KEY_NAME,employee,new CorrelationData(mailLog.getMsgId()));
            }
        });
    }
}
